package com.shangan.shortlink.admin.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shangan.shortlink.admin.dao.entity.GroupDO;
import com.shangan.shortlink.admin.dao.mapper.GroupMapper;
import com.shangan.shortlink.admin.service.GroupService;
import com.shangan.shortlink.admin.util.RandomStringGenerator;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * @author: Jerryzaj
 * @description TODO
 * @date: 2024/6/4 22:02
 */

/**
 * 短链接分组接口实现层
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {

    @Override
    public void save(String groupName) {
        String gid;
        do {
            gid = RandomStringGenerator.generateRandomString();
        } while (!(hasGid(gid)));
        GroupDO groupDO = GroupDO.builder()
                .gid(gid)
                .name(groupName)
                .build();
        baseMapper.insert(groupDO);
    }

    private boolean hasGid(String gid){

        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getId, gid)
                .eq(GroupDO::getDelFlag, 0)
                //TODO 设置用户名
                .eq(GroupDO::getUsername, null);
        GroupDO hasGroupFlag = baseMapper.selectOne(queryWrapper);
        return hasGroupFlag==null;
    }
}
